﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls;
using eBusiness.App_DAL;
using eBusiness.Models;

namespace eBusiness.Areas.Admin.Controllers
{
    [Authorize]
    public class CategoriesController : Controller
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();
        //
        // GET: /Categories/

        public ViewResult Index(int? pageNumber = 1, int? pageSize = 5, string softField = "CreatedDate", string softDir = "DESC")
        {
            try
            {
                ViewBag.CurrentSoftField = softField;
                ViewBag.CurrentSoftDir = softDir;

                var softdir = new List<ListItem> { new ListItem("Desc", "DESC"), new ListItem("Asc", "ASC") };
                ViewBag.SoftDir = new SelectList(softdir, softDir);

                var softFields = new List<ListItem>
                                 {
                                     new ListItem("Name", "Name"),
                                     new ListItem("ModifiedDate", "ModifiedDate"),
                                 };
                //ViewBag.SoftFields = new SelectList(softFields, Session["SoftField"]);
                ViewBag.SoftFields = new SelectList(softFields, softField);

                //apply filtering for get list Category

                var filterExpressions = new Collection<Expression<Func<Category, bool>>>();

                Expression<Func<Category, bool>> expressionLeft = (n => n.IsDeleted == false);

                filterExpressions.Add(expressionLeft);

                Func<IQueryable<Category>, IOrderedQueryable<Category>> orderby = (n => n.OrderByDescending(o => o.CreatedDate));

                switch (softDir.ToUpper())
                {
                    case "ASC":
                        if (softField != null && !string.IsNullOrEmpty(softField))
                        {
                            switch (softField)
                            {
                                case "Name":
                                    orderby = (product => product.OrderBy(p => p.Name));
                                    break;
                                case "ModifiedDate":
                                    orderby = (product => product.OrderBy(p => p.ModifiedDate));
                                    break;
                                default:
                                    orderby = (product => product.OrderBy(p => p.CreatedDate));
                                    break;
                            }
                        }
                        break;
                    case "DESC":
                        if (softField != null && !string.IsNullOrEmpty(softField))
                        {
                            switch (softField)
                            {
                                case "Name":
                                    orderby = (product => product.OrderByDescending(p => p.Name));
                                    break;
                                case "ModifiedDate":
                                    orderby = (product => product.OrderByDescending(p => p.ModifiedDate));
                                    break;
                                default:
                                    orderby = (product => product.OrderByDescending(p => p.CreatedDate));
                                    break;
                            }
                        }
                        break;
                }
                var news = _unitOfWork.CategoryRepository.Get(filters: filterExpressions, orderby: orderby);

                long numberOfRecord = news.Count();

                long numberOfPage = numberOfRecord % pageSize == 0
                                       ? numberOfRecord / pageSize.Value
                                       : numberOfRecord / pageSize.Value + 1;

                ViewBag.NumberOfPage = numberOfPage;
                ViewBag.CurrentPage = pageNumber;

                news = _unitOfWork.CategoryRepository.Get(filters: filterExpressions, orderby: orderby, pageSize: pageSize, pageNumber: pageNumber);

                return View(news.ToList());
            }
            catch (Exception)
            {
                
                return View("Error");
            }
        }

        //
        // GET: /Categories/Details/5

        public ViewResult Details(int id)
        {
            Category category = _unitOfWork.CategoryRepository.GetByID(id);
            return View(category);
        }

        //
        // GET: /Categories/Create

        public ActionResult Create()
        {
            ViewBag.Parents = new SelectList(_unitOfWork.CategoryRepository.Get(s => s.IsDeleted == false), "ID", "Name");
            return View();
        }

        //
        // POST: /Categories/Create

        [HttpPost]
        public ActionResult Create(Category category)
        {
            try
            {

                if (ModelState.IsValid)
                {
                    category.CreatedDate = DateTime.Now;
                    category.ModifiedDate = DateTime.Now;
                    var membershipUser = Membership.GetUser();
                    if (membershipUser != null)
                    {
                        var providerUserKey = membershipUser.ProviderUserKey;
                        if (providerUserKey != null)
                        {
                            category.CreatedBy = (Guid)providerUserKey;
                            category.ModifiedBy = (Guid)providerUserKey;
                        }
                    }

                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        var hpf = Request.Files[i] as HttpPostedFileBase;
                        if (hpf != null)
                        {
                            if (hpf.ContentLength == 0)
                                continue;

                            string savedFileName = AppDomain.CurrentDomain.BaseDirectory +
                                                   "\\Content\\images\\categories\\" + Path.GetFileName(hpf.FileName);
                            hpf.SaveAs(savedFileName);

                            category.Icon = "/Content/images/categories/" + Path.GetFileName(hpf.FileName);
                        }
                    }

                    _unitOfWork.CategoryRepository.Insert(category);
                    _unitOfWork.Save();

                    return RedirectToAction("Index");
                }
                ViewBag.Parents = new SelectList(_unitOfWork.CategoryRepository.Get(s => s.IsDeleted == false), "ID", "Name");
                return View(category);
            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        //
        // GET: /Categories/Edit/5

        public ActionResult Edit(int id)
        {
            try
            {
                Category category = _unitOfWork.CategoryRepository.GetByID(id);
                ViewBag.Parents = new SelectList(_unitOfWork.CategoryRepository.Get(s => s.IsDeleted == false && s.ID != id), "ID", "Name", category.ParentID);
                return View(category);
            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        //
        // POST: /Categories/Edit/5

        [HttpPost]
        public ActionResult Edit(Category category)
        {
            try
            {

                if (ModelState.IsValid)
                {
                    
                    category.ModifiedDate = DateTime.Now;
                    var membershipUser = Membership.GetUser();
                    if (membershipUser != null)
                    {
                        var providerUserKey = membershipUser.ProviderUserKey;
                        if (providerUserKey != null)
                        {
                    
                            category.ModifiedBy = (Guid)providerUserKey;
                        }
                    }

                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        var hpf = Request.Files[i] as HttpPostedFileBase;
                        if (hpf != null)
                        {
                            if (hpf.ContentLength == 0)
                                continue;

                            string savedFileName = AppDomain.CurrentDomain.BaseDirectory +
                                                   "\\Content\\images\\categories\\" + Path.GetFileName(hpf.FileName);
                            hpf.SaveAs(savedFileName);

                            category.Icon = "/Content/images/categories/" + Path.GetFileName(hpf.FileName);
                        }
                    }

                    _unitOfWork.CategoryRepository.Update(category);
                    _unitOfWork.Save();

                    return RedirectToAction("Index");
                }
                ViewBag.Parents = new SelectList(_unitOfWork.CategoryRepository.Get(s => s.IsDeleted == false && s.ID != category.ID), "ID", "Name", category.ParentID);
                return View(category);
            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        //
        // GET: /Categories/Delete/5

        public ActionResult Delete(int id)
        {
            Category category = _unitOfWork.CategoryRepository.GetByID(id);
            return View(category);
        }

        //
        // POST: /Categories/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                Category category = _unitOfWork.CategoryRepository.GetByID(id);

                category.IsDeleted = true;
                category.ModifiedDate = DateTime.Now;
                
                var membershipUser = Membership.GetUser();
                if (membershipUser != null)
                {
                    var providerUserKey = membershipUser.ProviderUserKey;
                    if (providerUserKey != null)
                    {

                        category.ModifiedBy = (Guid)providerUserKey;
                    }
                }

                _unitOfWork.CategoryRepository.Update(category);
                _unitOfWork.Save();

                return RedirectToAction("Index");
            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        protected override void Dispose(bool disposing)
        {
            _unitOfWork.Dispose();
            base.Dispose(disposing);
        }
    }
}